<template>
  <div class="container">
    <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="广告位置：" prop="position">
            <el-select v-model.trim="form.position" placeholder="广告位置" class="">
              <el-option v-for="item in selectAdvertising" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="广告类型：" prop="banner_type_id">
            <el-select v-model.trim="form.banner_type_id" placeholder="广告类型" class="">
              <el-option v-for="item in selectBannerType" :label="item.type_name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-tooltip placement="top" content="选择---无详情页面---时，无需填写商品id,和广告详情">
            <el-icon class="icon-wzg-config"><InfoFilled /></el-icon>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="广告名称：" prop="banner_name">
            <el-input v-model.trim="form.banner_name" placeholder="广告名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="商品id：" prop="goods_id">
            <el-input v-model.trim="form.goods_id" placeholder="商品id"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-tooltip placement="top" content="跳转到商品详情页面才需要填写">
            <el-icon class="icon-wzg-config"><InfoFilled /></el-icon>
          </el-tooltip>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="排序：" prop="sort">
            <el-input v-model.trim="form.sort" placeholder="排序"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="发布平台：" prop="platform_type">
            <el-select v-model.trim="form.platform_type" clearable multiple placeholder="请选择发布的平台" class="">
              <el-option v-for="item in selectPlatformList" :label="item.dictLabel" :value="item.dictValue" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="20">
          <el-form-item label="广告图片：" prop="image">
            <UploadImageInfo :imageWidth="imageWidth" :imageHeight="imageHeight" :suggestInfo="suggestInfo" v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="image" v-model:form="form" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="广告详情：" prop="detail">
            <div>
              <div id="editor"></div>
              <div>描述：通用活动页面的详情的展示</div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import UploadImageInfo from "@/components/common/UploadImageInfo.vue";
import { InfoFilled } from "@element-plus/icons-vue";
import type { postOrPutType } from "@/constants";
import type { AdvertisingType, ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IDictData } from "@/types/dict";
import type { IAdvertisingType } from "@/types/advertisingType";
import type { IAdvertisingDTO } from "@/types/advertisingInfo";
import { commonBannerInfo } from "@/utils/api/banner";
import { userEditor } from "@/hooks/userEditor";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  selectAdvertising: Array<IDictData>;
  selectPlatformList: Array<IDictData>;
  selectBannerType: Array<IAdvertisingType>;
}
const { selectAdvertising, selectPlatformList, selectBannerType } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });
const form = defineModel<IAdvertisingDTO>("form", { required: true });
const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
}>();
let { handleInitEditor } = userEditor("#editor", handleChangeNewHtml);
const isDisabledbtn = ref(false);
const editor = ref();
const suggestInfo = ref("建议：尺寸690*250,大小500k以下");
const imageWidth = ref<number>(690 / 2);
const imageHeight = ref<number>(250 / 2);
const formRef = useTemplateRef("formRef");
const methodType = ref<postOrPutType>("PUT");

defineExpose({
  editor
});

const rules = reactive({
  banner_name: [{ required: true, message: "请填写广告名称", trigger: "blur" }],
  position: [{ required: true, message: "请选择广告位置", trigger: "blur" }],
  banner_type_id: [{ required: true, message: "请选择广告类型", trigger: "blur" }],
  platform_type: [{ required: true, message: "请选择发布平台", trigger: "blur" }],
  sort: [{ required: true, message: "请填写排序", trigger: "blur" }],
  image: [{ required: true, message: "请上传广告图片", trigger: "blur" }]
});

onMounted(() => {
  editor.value = handleInitEditor();
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});

watch(
  () => form.value.position,
  newValue => {
    handleChangeAdvertising(newValue as AdvertisingType);
  }
);

/* 初始化数据 */
function handleInitData() {
  form.value.id = 0;
  methodType.value = "POST";
  isDisabledbtn.value = false;
  editor.value?.txt.clear();
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
  imageWidth.value = 690 / 2;
  imageHeight.value = 250 / 2;
  suggestInfo.value = `建议：尺寸${imageWidth.value * 2}*${imageHeight.value * 2},大小500k以下`;
}

/* 改变富文本内容 */
function handleChangeNewHtml(newHtml: string) {
  form.value.detail = newHtml;
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonBannerInfo(form.value, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch((err: Error) => {
      console.log(err);
    })
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  emit("handleInitData");
}

/* 修改广告位置 */
function handleChangeAdvertising(data: AdvertisingType) {
  console.log(1);

  const configMap = {
    aixzuRedPacketAdvertising: { width: 336, height: 440 },
    rentMachineBanner: { width: 340, height: 470 },
    aixzuDailySpecial: { width: 142, height: 165 },
    fzBanner: { width: 750, height: 600 },
    fzGoodsBanner: { width: 346, height: 490 },
    default: { width: 690, height: 250 }
  };

  const { width, height } = configMap[data] || configMap.default;
  const scaleFactor = 2; /* 需要二倍图 */

  imageWidth.value = width / scaleFactor;
  imageHeight.value = height / scaleFactor;
  suggestInfo.value = `建议：尺寸${width}*${height},大小500k以下`;
}
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}

/* 富文本编辑 start */
#editor {
  width: 397px;
  :deep(.w-e-toolbar) {
    z-index: 1001 !important;
  }
  :deep(.w-e-text-container) {
    z-index: 1000 !important;
  }
}
/* end */
</style>
